package com.ushio.gougouwangguo.task.job;

import com.ushio.gougouwangguo.entity.mysql.Resource;
import com.ushio.gougouwangguo.mapper.ResourceMapper;
import com.ushio.gougouwangguo.service.ResourceService;
import com.ushio.gougouwangguo.service.impl.ResourceServiceImpl;
import com.ushio.gougouwangguo.task.config.ResourceUpdateCallableTask;
import com.ushio.gougouwangguo.task.config.ResourceUpdateTask;
import com.ushio.gougouwangguo.utils.redis.ResourceRedisUtils;
import org.apache.ibatis.executor.BatchResult;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Component
public class PersistenceJob {

    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ResourceMapper resourceMapper;

    @Autowired
    ResourceRedisUtils resourceRedisUtils;

//    @Scheduled(cron = "0 */30 * * * ?")
    public void saveTheDatabase() {

        try {
            List<Resource> resources = resourceRedisUtils.getResource();

            if (!resources.isEmpty()) {
                List<List<Resource>> partitions = partition(resources, 2);

                List<Future<List<Resource>>> futures = new ArrayList<>();
                for (List<Resource> part : partitions) {
                    ResourceUpdateCallableTask task = new ResourceUpdateCallableTask(part, resourceMapper);
                    futures.add(executorService.submit(task));
                }

                List<Resource> updatedResources = new ArrayList<>();
                for (Future<List<Resource>> future : futures) {
                    try {
                        updatedResources.addAll(future.get());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("更新的数据条数：" + updatedResources.size());
                // resourceRedisUtils.delResource();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private <T> List<List<T>> partition(List<T> list, int size) {
        List<List<T>> parts = new ArrayList<>();
        for (int i = 0; i < list.size(); i += size) {
            parts.add(list.subList(i, Math.min(i + size, list.size())));
        }
        return parts;
    }
}

